package com.itheima.wallet.user.service;

import com.itheima.wallet.user.api.UserSendSmsServiceApi;
import com.itheima.wallet.user.vo.ErrorResult;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.Duration;

@Service(version = "1.0.0")
public class UserSendSmsService implements UserSendSmsServiceApi {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 根据手机号发送短信的方法
     * @param mobile 手机号
     * @return
     */
    @Override
    public String getSendSms(String mobile) {
        String code= "123456";
        return code;
    }

    @Override
    public ErrorResult sendCheckCode(String mobile) {
        try {
            //判断参数
            if(null==mobile){
                String mes = "参数有误";
                ErrorResult errorResult = new ErrorResult();
                errorResult.setErrCode("000003");
                errorResult.setErrMessage(mes);
                return errorResult;
            }

            //先判断redis中的验证码是否失效了
            String redisKey = "CHECK_CODE_"+mobile;
            if (this.redisTemplate.hasKey(redisKey)) {
                //如果redis中有该键则不用再次发
                //返货发送失败
                String mes = "验证码还没有失效";
                ErrorResult errorResult = new ErrorResult();
                errorResult.setErrCode("000000");
                errorResult.setErrMessage(mes);
                return errorResult;
            }
            //调用getSendSms方法发送验证码
            String code = this.getSendSms(mobile);
            //判断验证码是否为空
            if(null==code){
                //为空则发送验证码失败
                String mes = "发送验证码失败";
                ErrorResult errorResult = new ErrorResult();
                errorResult.setErrCode("000002");
                errorResult.setErrMessage(mes);

                return errorResult;
            }

            //如果成功的发送验证码，就把验证码存入到redis中
            this.redisTemplate.opsForValue().set(redisKey,code, Duration.ofMinutes(20));
            //this.redisTemplate.opsForValue().set(redisKey,code);

            //没有错误就返回null
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果出错
        String mes = "服务器内部错误";
        ErrorResult errorResult = new ErrorResult();
        errorResult.setErrCode("000004");
        errorResult.setErrMessage(mes);
        return errorResult;
    }


}
